package com.bed.lovewithpatientbed.config;

import com.bed.lovewithpatientbed.common.token.CustomUsernamePasswordToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author xuxiaoding
 * @version 1.0.0
 * @ClassName CustomModularRealmAuthenticator.java
 * @Description 自定义 ModularRealmAuthenticator，根据 Token中的类型选取不同 Realm 执行认证和授权
 */
@Slf4j
// @Component
public class CustomModularRealmAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.debug("CustomModularRealmAuthenticator.doAuthenticate");
        assertRealmsConfigured();
        log.info("Realms is not empty");
        CustomUsernamePasswordToken token = (CustomUsernamePasswordToken) authenticationToken;
        // 获取登录类型
        String loginSubjectType = token.getLoginSubjectType().getDesc();
        // 获取所有Realms
        Collection<Realm> realms = getRealms();
        // 存储登录类型对应Realm
        List<Realm> matchRealms = new ArrayList<>();
        // 循环匹配
        for (Realm realm : realms) {
            String realmName = realm.getName().substring(realm.getName().lastIndexOf(".") + 1);
            if (realmName.startsWith(loginSubjectType)) {
                matchRealms.add(realm);
            }
        }
        // 根据匹配 Realm 的不同数量执行不同的方法
        if (matchRealms.size() == 1) {
            log.info("doSingleRealmAuthentication: " + matchRealms.get(0).getName());
            return  doSingleRealmAuthentication(matchRealms.get(0), token);
        } else {
            log.info("doMultiRealmAuthentication");
            return  doMultiRealmAuthentication(matchRealms, token);
        }
    }
}
